package com.engine.zhlx.financemoduel.cashplan.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @author dusongsong
 * @date 2023年08月14日 11:20
 */
public class CashPlanUtil extends BaseBean {
    //建模权限重构
    public void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    //将数据插入表单建模
    public int insertModelData(int modeid, JSONObject paramJson) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        String sql = "select b.tablename,a.formid from modeinfo a left join workflow_bill b on a.formid=b.id where a.id=?";
        rs.executeQuery(sql, modeid);
        rs.next();
        String tablename = Util.null2String(rs.getString("tablename"));
        String uuid = UUID.randomUUID().toString();
        String insSql = "insert into " + tablename
                + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
        Object[] params = {uuid, 1, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
        if (rs.executeUpdate(insSql, params)) {
            rs1.executeQuery("select id from " + tablename + " where modeuuid=?", uuid);
            rs1.next();
            dataid = Util.getIntValue(rs1.getString("id"));
            if (dataid > 0) {
                Map<String, Object> map = JSONObject.toJavaObject(paramJson, Map.class);
                //遍历数据 进行update
                String updatesql = "update " + tablename + " set ";
                Set<String> keySet = map.keySet();
                for (String key : keySet) {
                    updatesql += key + "='" + map.get(key).toString() + "',";
                }
                if (updatesql.endsWith(",")) {
                    updatesql = updatesql.substring(0, updatesql.length() - 1);
                    updatesql += " where id=" + dataid;
                    rs.executeUpdate(updatesql);
                }
                //进行权限重构
                newModeRight(1, modeid, dataid);
            }
        }
        return dataid;
    }


    /**
     * 获取建模台账主键是否重复
     *
     * @param modeid
     * @param key
     * @return
     */
    public boolean isKeyExistByModel(int modeid, String key) {
        RecordSet rs = new RecordSet();
        String sql = "select b.tablename,a.formid from modeinfo a left join workflow_bill b on a.formid=b.id where a.id=?";
        rs.executeQuery(sql, modeid);
        rs.next();
        String tablename = Util.null2String(rs.getString("tablename"));
        rs.executeQuery("select count(id) from " + tablename + " where wyid=?", key);
        rs.next();
        return Util.getIntValue(rs.getString(1)) > 0;
    }

    /**
     * 获取流程银行流水号主键是否重复
     *
     * @param mainid
     * @param tablename
     * @param yxlsid
     * @return
     */
    public boolean isKeyExistByWf(String mainid, String tablename, String yxlsid) {
        RecordSet rs = new RecordSet();
        String sql = "select count(id) from " + tablename + " where mainid=? and yxlsid=?";
        rs.executeQuery(sql, mainid, yxlsid);
        rs.next();
        return Util.getIntValue(rs.getString(1)) > 0;
    }

    /**
     * 判断建模ID是否存在
     */
    public boolean isModelId(int modelId) {
        RecordSet rs = new RecordSet();
        String sql = "select count(id) from modeinfo  where id=?";
        rs.executeQuery(sql, modelId);
        rs.next();
        return Util.getIntValue(rs.getString(1), -1) > 0;
    }

    /**
     * 获取流程主表ID
     */
    public String getMainidByReq(String requestid, String formid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from formtable_main_" + formid + " where requestid=?", requestid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 更新用款台账金额	是否已支付完成
     */
    public boolean updateYbyktz(String requestid, String sfje, String field, String formId, String formtype) {
        RecordSet rs = new RecordSet();
        boolean flag;
        String tablenamedtl = "formtable_main_" + formId + "_" + formtype;
        String tablename = "formtable_main_" + formId;
        rs.executeQuery("select id," + field + " from " + tablename + " where requestid=?", requestid);
        rs.next();
        String mainid = Util.null2String(rs.getString(1));
        String bcqkjehj = Util.null2String(rs.getString(field));
        rs.executeQuery("select sum(sfje) from " + tablenamedtl + " where mainid=?", mainid);
        rs.next();
        String sfjehj = fAdd(sfje, Util.null2String(rs.getString(1), "0"));
        if (fCompare(bcqkjehj, sfjehj) == 0) {
            flag = rs.executeUpdate("update uf_ybyktz set sfyzfwc=?,yzfje=? where fklc=?", "0", sfjehj, requestid);
        } else {
            flag = rs.executeUpdate("update uf_ybyktz set sfyzfwc=?,yzfje=? where fklc=?", "1", sfjehj, requestid);
        }
        return flag;
    }

    /**
     * 更新明细表单信息
     */
    public boolean updateDetailData(String tablename, JSONObject paramJson) {
        String insertsql = "insert into " + tablename + "";
        String keyString = "";
        String valueString = "";
        Map<String, Object> map = JSONObject.toJavaObject(paramJson, Map.class);
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (map.get(key) == null || "".equals(map.get(key).toString())) {
                continue;
            }
            keyString += key + ",";
            valueString += "'" + map.get(key).toString() + "',";
        }
        if (keyString.endsWith(",")) {
            keyString = keyString.substring(0, keyString.length() - 1);
        }
        if (valueString.endsWith(",")) {
            valueString = valueString.substring(0, valueString.length() - 1);
        }
        insertsql += "(" + keyString + ") values(" + valueString + ")";
        writeLog(">>>>>updateDetailData>>>>insertsql=" + insertsql);
        RecordSet rs = new RecordSet();
        return rs.executeUpdate(insertsql);
    }

    /**
     * 判断是否是JSON数组
     */
    public boolean isJSONArray(String fieldvalue) {
        boolean flag = false;
        if (!(fieldvalue.equals(""))) {
            try {
                JSONArray.parseArray(fieldvalue);
                flag = true;
            } catch (Exception e) {
                flag = false;
            }
        }
        return flag;
    }

    // 大小比较 -1 0 1
    public int fCompare(String a, String b) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);

        return bg1.compareTo(bg2);
    }

    // f点型相加
    public String fAdd(String a, String b) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);

        BigDecimal bd = bg1.add(bg2);

        return bd.toString();
    }

    public String isZero(String a) {
        if ("".equals(a)) {
            a = "0";
        }
        return a;
    }


}
